package stat;

public class LinearEquationSystem {

	// Ax=b

	private Matrix A; //A

	private Matrix b; //b

	private Matrix x; //x

	public LinearEquationSystem(Matrix a, Matrix b) {
		initES(a, b);
	}

	public void initES(Matrix a, Matrix b) {
		this.A = a;
		this.b = b;

		if (!isValid()) {
			System.err.println("ES input matrices invalid");
		}
	}

	public boolean isValid() {
		return (A.numberOfRows() == b.numberOfRows()) &&
			   (A.numberOfRows() == A.numberOfCols());
	}

	public void calculate() {
		Matrix Ap = A.inverse();
		x = Ap.multiply(b);
	}

	public double xOf(int i) {
		if (i < 0 || i >= x.numberOfRows()) {
			System.err.println("ES xOf index out of bound");
			return 0;
		}

		return x.valueAt(i, 0);
	}

	public Matrix getX() {
		return x;
	}

	public static void main(String[] args) {
		Matrix m = new Matrix(3,3);
		m.setValueAt(0, 0, 1);
		m.setValueAt(0, 1, 2);
		m.setValueAt(0, 2, 5);
		m.setValueAt(1, 1, 2);
		m.setValueAt(2, 2, 2);
		m.setValueAt(2, 0, 1);
		m.print();

		Matrix mm = new Matrix(3,1);
		mm.setValueAt(0, 0, 1);
		mm.setValueAt(1, 0, 2);
		mm.setValueAt(2, 0, 2);
		mm.print();

		LinearEquationSystem es = new LinearEquationSystem(m, mm);
		es.calculate();

		es.getX().transpose().print();
	}
}
